package com.huawei.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import com.huawei.common.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author LF
 * projectName:vue-cli
 * description:生成验证码
 * time:2025-04-29 22:42
 */
@RestController
@RequestMapping("captcha")
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("getCaptcha")
    public BaseResult<Map<String, String>> getCaptcha() {
        //1、hutool工具类生成验证码
        GifCaptcha captcha = CaptchaUtil.createGifCaptcha(100, 40, 6);
        //2、生成uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //3、将验证码和uuid存入redis
        redisTemplate.opsForValue().set("captcha:" + uuid, captcha.getCode(), 5, TimeUnit.MINUTES);
        //4、获取验证码图片的base64编码
        String base64 = captcha.getImageBase64();
        //5、封装返回结果
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("uuid", uuid);
        resultMap.put("img", base64);
        return BaseResult.success(resultMap);
    }
}
